<script>
import axios from "../../axios/axiosHelper";
import { Plus, Search, Edit, Delete, ShoppingCart } from '@element-plus/icons-vue';

export default {
  name: "ShopCart",
  components: {
    Plus,
    Search,
    Edit,
    Delete,
    ShoppingCart
  },
  data() {
    return {
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      searchForm: {
        field: '',
        code: ''
      },
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: '',
        member_id: '',
        book_id: '',
        quantity: 1,
        create_time: '',
        update_time: ''
      },
      rules: {
        member_id: [
          { required: true, message: '请选择会员', trigger: 'change' }
        ],
        book_id: [
          { required: true, message: '请选择图书', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              const num = Number(value);
              if (isNaN(num) || num < 1) {
                callback(new Error('数量必须大于0'));
              } else {
                callback();
              }
            }, 
            trigger: 'blur' 
          }
        ]
      },
      memberList: [],
      bookList: []
    };
  },
  created() {
    this.fetchMemberList();
    this.fetchBookList();
    this.fetchData();
  },
  methods: {
    // 获取购物车数据
    fetchData() {
      this.loading = true;
      
      // 确保会员列表和图书列表已加载
      if (this.memberList.length === 0) {
        this.fetchMemberList();
      }
      
      if (this.bookList.length === 0) {
        this.fetchBookList();
      }
      
      const params = {
        offset: (this.currentPage - 1) * this.pageSize,
        limit: this.pageSize
      };
      
      // 添加搜索条件
      if (this.searchForm.code) {
        params.field = 'cart_no,member_name,book_name';
        params.code = this.searchForm.code;
      }
      
      axios.get('/shop-cart/list', { params }).then(response => {
        this.tableData = response.data.rows || [];
        this.total = response.data.total || 0;
        this.loading = false;
      }).catch(error => {
        console.error('获取购物车数据失败:', error);
        if (error.code === 'ECONNREFUSED' || error.message.includes('Network Error')) {
          this.$message.error('后端服务未启动，无法获取数据');
        } else {
          this.$message.error('获取购物车数据失败: ' + (error.response?.data?.message || error.message));
        }
        this.tableData = [];
        this.total = 0;
        this.loading = false;
      });
    },
    // 获取会员列表
    fetchMemberList() {
      return axios.get('/member/all').then(response => {
        this.memberList = response.data;
        return response.data;
      }).catch(error => {
        console.error('获取会员列表失败:', error);
        this.$message.error('获取会员列表失败');
        return [];
      });
    },
    // 获取图书列表
    fetchBookList() {
      return axios.get('/book/all').then(response => {
        this.bookList = response.data;
        return response.data;
      }).catch(error => {
        console.error('获取图书列表失败:', error);
        this.$message.error('获取图书列表失败');
        return [];
      });
    },
    // 处理页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchData();
    },
    // 打开添加对话框
    handleAdd() {
      this.dialogTitle = '添加购物车';
      this.form = {
        id: '',
        member_id: '',
        book_id: '',
        quantity: 1,
        create_time: new Date().toISOString().replace('T', ' ').split('.')[0],
        update_time: new Date().toISOString().replace('T', ' ').split('.')[0]
      };
      this.dialogVisible = true;
    },

    // 编辑购物车
    handleEdit(index, row) {
      this.dialogTitle = '编辑购物车';
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 额外验证
          if (!this.form.member_id) {
            this.$message.error('请选择会员');
            return;
          }
          if (!this.form.book_id) {
            this.$message.error('请选择图书');
            return;
          }
          if (this.form.quantity <= 0) {
            this.$message.error('数量必须大于0');
            return;
          }
          
          this.loading = true;
          
          const formData = {
            ...this.form,
            quantity: Number(this.form.quantity)
          };
          
          if (this.form.id) {
            // 更新
            axios.put('/shop-cart/update', formData).then(response => {
              this.$message.success('更新成功');
              this.dialogVisible = false;
              this.fetchData();
              this.loading = false;
            }).catch(error => {
              console.error('更新购物车失败:', error);
              if (error.code === 'ECONNREFUSED' || error.message.includes('Network Error')) {
                this.$message.error('后端服务未启动，请联系管理员');
              } else {
                this.$message.error('更新购物车失败: ' + (error.response?.data?.message || error.message));
              }
              this.loading = false;
            });
          } else {
            // 添加
            axios.post('/shop-cart/add', formData).then(response => {
              this.$message.success('添加成功');
              this.dialogVisible = false;
              this.fetchData();
              this.loading = false;
            }).catch(error => {
              console.error('添加购物车失败:', error);
              if (error.code === 'ECONNREFUSED' || error.message.includes('Network Error')) {
                this.$message.error('后端服务未启动，请联系管理员');
              } else {
                this.$message.error('添加购物车失败: ' + (error.response?.data?.message || error.message));
              }
              this.loading = false;
            });
          }
        } else {
          this.$message.error('请检查表单填写是否正确');
          return false;
        }
      });
    },
    // 重置表单
    resetForm() {
      this.$refs.form.resetFields();
      this.form = {
        id: '',
        member_id: '',
        book_id: '',
        quantity: 1,
        create_time: '',
        update_time: ''
      };
    },
    // 关闭对话框
    handleDialogClose() {
      this.dialogVisible = false;
      this.resetForm();
    },
    // 删除购物车
    handleDelete(index, row) {
      this.$confirm('确认删除该购物车记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        axios.delete(`/shop-cart/delete/${row.id}`).then(response => {
          this.$message.success('删除成功');
          this.fetchData();
          this.loading = false;
        }).catch(error => {
          console.error('删除购物车失败:', error);
          this.$message.error('删除购物车失败');
          this.loading = false;
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 获取状态名称
    getStatusName(status) {
      const statusObj = this.statusOptions.find(item => item.value === status);
      return statusObj ? statusObj.label : '未知状态';
    }
  }
}
</script>

<template>
  <div class="cart-container">
    <!-- 标题栏 -->
    <div class="header">
      <div class="title-section">
        <h2 class="page-title">购物车表</h2>
        <el-button type="primary" size="small" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加购物车
        </el-button>
      </div>
      <div class="search">
        <el-input v-model="searchForm.code" placeholder="请输入购物车号/会员名称/图书名称搜索..." clearable size="small" style="width: 300px;">
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" size="small" @click="fetchData">搜索</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        v-loading="loading"
        element-loading-text="加载中..."
        :header-cell-style="{backgroundColor: '#f5f7fa', color: '#606266'}"
        highlight-current-row
        stripe
      >
        <el-table-column type="index" min-width="5%" align="center" label="序号"></el-table-column>
        <el-table-column prop="id" label="ID" min-width="8%" align="center"></el-table-column>
        <el-table-column prop="memb_id" label="会员ID" min-width="10%" align="center"></el-table-column>
        <el-table-column prop="book_id" label="图书ID" min-width="10%" align="center"></el-table-column>
        <el-table-column prop="book_num" label="图书数量" min-width="10%" align="center"></el-table-column>
        <el-table-column prop="create_time" label="创建时间" min-width="15%" align="center">
          <template #default="scope">
            {{ scope.row.create_time ? new Date(scope.row.create_time).toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="update_time" label="更新时间" min-width="15%" align="center">
          <template #default="scope">
            {{ scope.row.update_time ? new Date(scope.row.update_time).toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="10%" align="center">
          <template #default="scope">
            <div class="operation-buttons">
              <el-tooltip content="编辑" placement="top" :hide-after="1500">
                <el-button type="primary" circle size="small" @click="handleEdit(scope.$index, scope.row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" :hide-after="1500">
                <el-button type="danger" circle size="small" @click="handleDelete(scope.$index, scope.row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="550px" 
      :close-on-click-modal="false"
      destroy-on-close
      center
      class="custom-dialog"
      @close="handleDialogClose"
    >
      <div class="dialog-content">
        <el-form 
          :model="form" 
          :rules="rules" 
          ref="form" 
          label-width="120px"
          class="cart-form"
          status-icon
        >
          <el-form-item label="会员" prop="member_id">
            <el-select 
              v-model="form.member_id" 
              placeholder="请选择会员" 
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in memberList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="图书" prop="book_id">
            <el-select 
              v-model="form.book_id" 
              placeholder="请选择图书" 
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in bookList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数量" prop="quantity">
            <el-input-number 
              v-model="form.quantity" 
              :min="1"
              style="width: 100%"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="创建时间" prop="create_time">
            <el-input 
              v-model="form.create_time" 
              placeholder="系统自动生成"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="更新时间" prop="update_time">
            <el-input 
              v-model="form.update_time" 
              placeholder="系统自动生成"
              disabled
            ></el-input>
          </el-form-item>

        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetForm" plain>重 置</el-button>
          <el-button @click="dialogVisible = false" plain>取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style>
.cart-container {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  overflow: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  color: #303133;
  font-weight: 600;
  position: relative;
  padding-left: 12px;
}

.page-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: #409EFF;
  border-radius: 2px;
}

.search {
  display: flex;
  gap: 10px;
  align-items: center;
}

.table-container {
  background-color: #fff;
  border-radius: 6px;
  padding: 10px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  flex: 1;
  overflow: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.cart-form .el-form-item {
  margin-bottom: 20px;
}

.dialog-content {
  padding: 0 10px;
}

.custom-dialog .el-dialog__body {
  padding: 20px 20px 10px 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.custom-dialog .el-dialog__header {
  padding: 10px;
  margin: 0;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.custom-dialog .el-dialog__title {
  font-weight: 600;
  color: #303133;
  font-size: 18px;
}

.custom-dialog .el-dialog__body {
  padding: 20px 10px;
}

.custom-dialog .el-dialog__footer {
  padding: 10px;
  border-top: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.dialog-content {
  max-height: 60vh;
  overflow-y: auto;
}
</style>